//
//  ImageLoadingOperation.m
//  MyTableView


#import "ImageLoadingOperation.h"

NSString *const ResultKey = @"result";
NSString *const ImageKey = @"image";
NSString *const URLKey = @"url";

@implementation ImageLoadingOperation

- (id)initWithImageURL:(NSURL *)theImageURL target:(id)theTarget action:(SEL)theAction
{
    self = [super init];
    if (self) {
        imageURL = [theImageURL retain];
        target = theTarget;
        action = theAction;
		notifyList = [[NSMutableArray alloc] init];
		notifyLock = [[NSLock alloc] init];
    }
    return self;
}

- (BOOL)isConcurrent {

    return YES;
}

- (void)dealloc
{
    [imageURL release];
    [notifyList release];
	[notifyLock release];
    [super dealloc];
}

- (void)main
{
    NSData *data = [[NSData alloc] initWithContentsOfURL:imageURL];
	if (data == nil) 
	{
		NSDictionary *failResult = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], ResultKey, nil, ImageKey, imageURL, URLKey, nil];
		[target performSelectorOnMainThread:action withObject:failResult waitUntilDone:YES];
		return;
    }
	
    UIImage *image = [[UIImage alloc] initWithData:data];
	
//	[notifyLock lock];
	for (int i=0; i<[notifyList count]; i++) 
	{
        if ([notifyList objectAtIndex:i] != nil) {
            if([[notifyList objectAtIndex:i] respondsToSelector:@selector(didLoadImage:Image:)]) {
                
                [[notifyList objectAtIndex:i] didLoadImage:imageURL Image:image];
            }
        }
	}
    
    NSDictionary *result = [NSDictionary dictionaryWithObjectsAndKeys:image, ImageKey, imageURL, URLKey, nil];
    if(target != nil ) {
        [target performSelectorOnMainThread:action withObject:result waitUntilDone:NO];
    }
    
//	[notifyLock unlock];
 
    [data release];
    [image release];
}

- (void)addNotify:(id<ImageLoadingDelegate>)delegate {
	[notifyLock lock];
	[notifyList addObject:delegate];
	[notifyLock unlock];
}

- (void)cancel {

    target = nil;
    action = nil;
    [notifyList removeAllObjects];
    
    [super cancel];
}

@end
